//
//  DHSearchColorCell.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/2/10.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHSearchColorCell.h"
#import "DHSearchColorItem.h"
#import "Color.h"

@interface DHSearchColorCell()

@property (strong, nonatomic) UIScrollView *scrollView;

@property (strong, nonatomic) NSArray *dataArr;

@end

@implementation DHSearchColorCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        if (!self.scrollView) {
            self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 54)];
            [self.contentView addSubview:self.scrollView];
        }
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 53, kScreenWidth, 1)];
        line.backgroundColor = [UIColor colorWithHexString:@"#ECF2F1"];
        [self.contentView addSubview:line];
    }
    return self;
}

- (NSArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSArray array];
    }
    return _dataArr;
}

- (void)layoutSubviews{
    self.scrollView.frame = CGRectMake(0, 0, self.width, self.height);
}

- (void)updateCellWithConditionArr:(NSArray *)conditionArr firstLoad:(BOOL)firstLoad{
    self.dataArr = conditionArr;
    if (firstLoad) {
        [self.scrollView removeAllSubviews];
        self.dataArr = conditionArr;
        CGFloat W = 42;
        __weak __typeof(self)weakSelf = self;
        self.scrollView.contentSize = CGSizeMake(conditionArr.count * W, self.height);
        [conditionArr enumerateObjectsUsingBlock:^(Color *color, NSUInteger idx, BOOL * _Nonnull stop) {
            DHSearchColorItem *colorItemView = [[DHSearchColorItem alloc] initWithFrame:CGRectMake(idx * W, 0, W, weakSelf.height) andColor:color.color];
            [weakSelf.scrollView addSubview:colorItemView];
            colorItemView.tag = idx;
            [colorItemView addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
        }];
    }
}

- (void)clickAction:(UIControl *)sender{
    for (DHSearchColorItem *item in self.scrollView.subviews) {
        if (item.tag != sender.tag) {
            item.selected = YES;
            [item selectColor:item];
        }
    }
    Color *color = self.dataArr[sender.tag];
    if (sender.isSelected) {
        [self routerEventWithName:@"DHSearchColorCell" userInfo:@{@"color_name":color.name}];
    }else{
        [self routerEventWithName:@"DHSearchColorCell" userInfo:@{@"color_name":[NSNull null]}];
    }
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
